package com.kh.rationaldrugreview.controller;

import com.kh.rationaldrugreview.dto.PrescriptionRiskAssessmentRequest;
import com.kh.rationaldrugreview.dto.PrescriptionRiskAssessmentResponse;
import com.kh.rationaldrugreview.service.KnowledgeGraphRiskAssessmentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 处方风险评估控制器
 * Prescription Risk Assessment Controller
 */
@Slf4j
@RestController
@RequestMapping("/api/risk-assessment")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class PrescriptionRiskAssessmentController {
    
    private final KnowledgeGraphRiskAssessmentService riskAssessmentService;
    
    /**
     * 评估处方风险
     */
    @PostMapping("/evaluate")
    public ResponseEntity<PrescriptionRiskAssessmentResponse> evaluateRisk(
            @RequestBody PrescriptionRiskAssessmentRequest request) {
        
        log.info("Received risk assessment request for patient: {}, drugs count: {}", 
            request.getPatient() != null ? request.getPatient().getName() : "Unknown",
            request.getDrugs() != null ? request.getDrugs().size() : 0);
        
        try {
            PrescriptionRiskAssessmentResponse response = riskAssessmentService.assessPrescriptionRisk(request);
            
            if (response.getStatus() == PrescriptionRiskAssessmentResponse.AssessmentStatus.ERROR) {
                return ResponseEntity.badRequest().body(response);
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Error in risk assessment endpoint", e);
            
            PrescriptionRiskAssessmentResponse errorResponse = PrescriptionRiskAssessmentResponse.builder()
                .assessmentId("ERROR_" + System.currentTimeMillis())
                .status(PrescriptionRiskAssessmentResponse.AssessmentStatus.ERROR)
                .summary("服务器内部错误")
                .riskItems(List.of())
                .recommendations(List.of())
                .assessmentTime(java.time.LocalDateTime.now())
                .build();
            
            return ResponseEntity.internalServerError().body(errorResponse);
        }
    }
    
    /**
     * 快速风险筛查
     */
    @PostMapping("/quick-screening")
    public ResponseEntity<PrescriptionRiskAssessmentResponse> quickScreening(
            @RequestBody PrescriptionRiskAssessmentRequest request) {
        
        log.info("Received quick screening request");
        
        try {
            PrescriptionRiskAssessmentResponse response = riskAssessmentService.quickScreening(request);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Error in quick screening endpoint", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 批量风险评估
     */
    @PostMapping("/batch")
    public ResponseEntity<PrescriptionRiskAssessmentResponse> batchEvaluate(
            @RequestBody List<PrescriptionRiskAssessmentRequest> requests) {
        
        log.info("Received batch risk assessment request for {} prescriptions", requests.size());
        
        try {
            PrescriptionRiskAssessmentResponse response = riskAssessmentService.batchAssess(
                requests.toArray(new PrescriptionRiskAssessmentRequest[0]));
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Error in batch assessment endpoint", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取风险规则说明
     */
    @GetMapping("/rules")
    public ResponseEntity<Map<String, Object>> getRiskRules() {
        Map<String, Object> rules = new HashMap<>();
        
        // 风险等级说明
        Map<String, String> riskLevels = Map.of(
            "CRITICAL", "极高风险 - 绝对禁忌、妊娠X级、严重相互作用",
            "HIGH", "高风险 - 相对禁忌、妊娠D级、重度器官功能不全",
            "MEDIUM", "中风险 - 妊娠C级、年龄限制、中度相互作用",
            "LOW", "低风险 - 妊娠B级、轻微相互作用",
            "NONE", "无风险 - 妊娠A级、无相互作用"
        );
        
        // 检查类型说明
        Map<String, String> checkTypes = Map.of(
            "DRUG_INTERACTION", "药物相互作用检查",
            "PREGNANCY_RISK", "妊娠期用药风险检查",
            "CONTRAINDICATION", "禁忌症检查",
            "ORGAN_FUNCTION", "器官功能相关风险检查",
            "AGE_RESTRICTION", "年龄适用性检查",
            "ALLERGY_RISK", "过敏风险检查",
            "DUPLICATION", "重复用药检查"
        );
        
        // 评估选项说明
        Map<String, String> assessmentOptions = Map.of(
            "基础", "仅检查高风险项（相互作用、禁忌症、妊娠风险）",
            "标准", "检查常见风险项（包含年龄、器官功能等）",
            "全面", "检查所有风险项（包含轻微风险和重复用药）"
        );
        
        rules.put("riskLevels", riskLevels);
        rules.put("checkTypes", checkTypes);
        rules.put("assessmentOptions", assessmentOptions);
        rules.put("version", "1.0");
        rules.put("lastUpdated", java.time.LocalDateTime.now());
        
        return ResponseEntity.ok(rules);
    }
    
    /**
     * 健康检查
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> healthCheck() {
        Map<String, Object> health = new HashMap<>();
        health.put("status", "UP");
        health.put("service", "Risk Assessment Service");
        health.put("timestamp", java.time.LocalDateTime.now());
        health.put("version", "1.0");
        
        return ResponseEntity.ok(health);
    }
    
    /**
     * 获取支持的患者特征
     */
    @GetMapping("/patient-features")
    public ResponseEntity<Map<String, Object>> getPatientFeatures() {
        Map<String, Object> features = new HashMap<>();
        
        features.put("ageGroups", List.of("新生儿", "幼儿", "儿童", "青少年", "成人", "老年人"));
        features.put("genders", List.of("男", "女"));
        features.put("pregnancyStatuses", List.of("未怀孕", "孕早期", "孕中期", "孕晚期"));
        features.put("lactationStatuses", List.of("非哺乳期", "哺乳期"));
        features.put("renalFunctions", List.of("正常", "轻度不全", "中度不全", "重度不全", "透析"));
        features.put("hepaticFunctions", List.of("正常", "轻度不全", "中度不全", "重度不全"));
        features.put("pregnancyCategories", List.of("A", "B", "C", "D", "X"));
        
        return ResponseEntity.ok(features);
    }
    
    /**
     * 示例请求
     */
    @GetMapping("/example")
    public ResponseEntity<PrescriptionRiskAssessmentRequest> getExampleRequest() {
        PrescriptionRiskAssessmentRequest example = PrescriptionRiskAssessmentRequest.builder()
            .patient(PrescriptionRiskAssessmentRequest.PatientInfo.builder()
                .name("张三")
                .gender("女")
                .age(28)
                .weight(65.0)
                .height(165.0)
                .isPregnant(true)
                .pregnancyTrimester("孕中期")
                .gestationalWeek(20)
                .isLactating(false)
                .renalFunction("正常")
                .hepaticFunction("正常")
                .medicalHistory(List.of("高血压"))
                .allergies(List.of("青霉素"))
                .build())
            .drugs(List.of(
                PrescriptionRiskAssessmentRequest.PrescriptionDrug.builder()
                    .drugName("阿司匹林")
                    .genericName("乙酰水杨酸")
                    .dosage(new java.math.BigDecimal("100"))
                    .dosageUnit("mg")
                    .frequency("每日一次")
                    .administration("口服")
                    .duration(30)
                    .activeIngredient("乙酰水杨酸")
                    .build(),
                PrescriptionRiskAssessmentRequest.PrescriptionDrug.builder()
                    .drugName("叶酸片")
                    .genericName("叶酸")
                    .dosage(new java.math.BigDecimal("5"))
                    .dosageUnit("mg")
                    .frequency("每日一次")
                    .administration("口服")
                    .duration(90)
                    .activeIngredient("叶酸")
                    .build()
            ))
            .diagnoses(List.of("妊娠期高血压"))
            .options(PrescriptionRiskAssessmentRequest.AssessmentOptions.createDefault())
            .build();
        
        return ResponseEntity.ok(example);
    }
}